import {
  getAllTeamInfosByRoleType,
  updateTeamInfosByRoleType,
  addTeamInfoByRoleType,
  delTeamInfosByRoleType,
  getRole,
  getAllUser,
  getUserInfoSimp,
  getUserByRoleType,
  delOneTeamMember,
} from '@/services/system/teamInfo';
import { PlusOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tag, Select, Tooltip } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { Ellipsis } from '@/components/Ellipsis';
import { history } from 'umi';
const TeamInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [optionsUpdate, setoptionsUpdate] = useState([]);
  const [userOptions, setUserOptions] = useState([]);
  const [form] = Form.useForm();
  const [allMenmer, setAllMenber] = useState([{ value: null, label: null }]);
  const [rowInfo, setRowInfo] = useState();

  useEffect(() => {
    actionRef.current!.reload();
  }, [history?.location?.state?.id]);

  //角色类别更换的时候需要更换用户列表
  const getMenberByType = async (type: string) => {
    const result = await getUserByRoleType(type);
    let options = result.data.map((item: any) => {
      return { label: item.userName, value: item.userId };
    });
    if (options.length == 0) {
      options = [{ value: null, lable: null }];
    }
    setAllMenber(options);
  };

  const handleFilterChange = (filters) => {
    // 处理筛选框值的变化事件
    console.log('筛选框值变化:', filters);
    // 根据需要进行相应的操作，比如重新请求数据等
  };
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 10,
    },
    {
      title: '用户名称',
      dataIndex: 'teamInfoEx',
      width: 90,
      align: 'center',
      sorter: true,
      valueType: 'select',
      request: async () => {
        const result = await getUserInfoSimp(null);
        const tempUser: any = [];
        result.data.map((item: any, index: number) => {
          tempUser.push({ value: item.userId, label: item.userName });
        });
        return tempUser;
      },
      // render: (text) => <>{Ellipsis(text)}</>,
      // render: (text) => {
      //   const temp = text.split(',').map((item) => {
      //     return <Tag color="blue">{item}</Tag>;
      //   });
      //   return temp;
      //   // return <>{Ellipsis(text)}</>;
      // },
    },
    // {
    //   title: '角色名称',
    //   dataIndex: 'roleName',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '角色类别',
      dataIndex: 'roleType',
      width: 50,
      align: 'center',
      sorter: true,
      valueType: 'select',
      request: async () => {
        const roleInfo = await getRole(null);
        const allRole: any[] = [];
        roleInfo.data.map((item: any) => {
          allRole.push({ value: item, label: item });
        });
        return allRole;
      },
      render: (text) => <>{Ellipsis(text)}</>,
    },

    // {
    //   title: '角色ID',
    //   dataIndex: 'roleId',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },

    // {
    //   title: '流水号',
    //   dataIndex: 'serialNo',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },

    // {
    //   title: '创建日期', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createTime',
    //   width: 120,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    // {
    //   title: '创建人', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createName',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   search: false,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 50,
      render: (text, record, _, action) => [
        /*         <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            setRowInfo(record?.info);
            form.setFieldsValue({
              category: record.roleType,
              memo: record.memo,
              reserved: record.reserved,
              roleId: record.roleId,
              roleName: record.roleName,
              serialNo: record.serialNo,
              userId: record.userId,
              userName: record.teamInfoEx.split(','),
              teamId: record.teamId,
            });
          }}
        >
          编辑
        </a>, */
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                console.log(record, 'record');
                let res = {};
                res.teamId = record.teamId;
                res.userId = record.info[0].userId;
                res.roleId = record.info[0].roleId;
                console.log(res, 'API');
                const result = await delOneTeamMember(res);
                /*                 const result = await delTeamInfosByRoleType({
                  teamId: record.teamId,
                  roleType: record.roleType,
                }); */
                if (result && result.code == 0) {
                  message.success('删除成功');
                }
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle === '新建') {
      form
        .validateFields()
        .then(async (value) => {
          const res = { ...form.getFieldsValue(), teamId: history.location.state!.id };
          const temp = {
            roleType: res.category,
            teamId: res.teamId,
            userIds: res.userName,
          };
          const result = await addTeamInfoByRoleType(temp);
          if (result != null) {
            message.success('添加成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
        })
        .catch((err) => {
          setConfirmLoading(false);
        });
      actionRef.current!.reload();
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = { ...form.getFieldsValue(), teamId: history.location.state.id };
          const temps = [];
          res.userName.forEach((item: any) => {
            rowInfo.map((ele: any) => {
              if (item === ele.userName) {
                temps.push(ele.userId);
              }
            });
          });
          console.log(res, 'ressssssss');
          console.log(rowInfo, 'rowInfo');
          const temp = {
            roleType: res.category,
            teamId: res.teamId,
            userIds: temps,
          };
          const result = await updateTeamInfosByRoleType(temp);
          if (result != null) {
            message.success('修改成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
    actionRef.current!.reload();
  };
  const getTeamInfo = async () => {
    const result = await getUserInfoSimp(null);
    const tempUser: any = [];
    result.data.map((item: any, index: number) => {
      tempUser.push({ value: item.userId, label: item.userName });
    });
    setUserOptions(tempUser);
  };

  const splitRes = (data: any) => {
    let resAfterSplit = new Array();
    let tempTeamInfoEx = new Array();
    data.map((item: any) => {
      tempTeamInfoEx = []; //先清空
      tempTeamInfoEx = item.teamInfoEx.split(','); //然后接收
      for (let i = 0; i < item.info.length; i++) {
        let temp = {};
        let tempInfo = [];
        tempInfo.push(item.info[i]); //把info给放进去
        temp.info = tempInfo;
        temp.roleType = item.roleType;
        temp.teamId = item.teamId;
        temp.teamInfoEx = tempTeamInfoEx[i];
        resAfterSplit.push(temp);
      }
    });
    return resAfterSplit;
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="团队成员信息查询"
        actionRef={actionRef} //用于触发刷 新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        revalidateOnFocus={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<ArrowLeftOutlined />}
            onClick={() => {
              history.push('/basicData/team');
            }}
            type="primary"
          >
            返回
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(history.location.state.id, 'history.location.state.id');
          // const res = { ...params, teamId: history.location.state.id };
          // const sorters = sortTran(sort);
          // const filters = filterTran(res);
          // const result = await getTeamInfoByPage({ ...params, sorters: sorters, filters: filters });
          const result = await getAllTeamInfosByRoleType(history.location.state.id);
          console.log(result, 'res');
          if (result && result?.data && result.data.length !== 0) {
            result.data.forEach((item: any) => {
              const infos: any[] = [];
              const allInfos: any[] = [];
              item.teamInfoEx.forEach((ele: any) => {
                infos.push(ele.userName);
                allInfos.push({ userId: ele.userId, userName: ele.userName, roleId: ele.roleId });
              });
              item.info = allInfos;
              item.teamInfoEx = infos.join(',');
            });
          }
          let resultAfterSplit = splitRes(result.data);
          //获取系统所有用户
          const roleInfo = await getRole(null);
          const allRole: any[] = [];
          roleInfo.data.map((item: any) => {
            allRole.push({ value: item, label: item });
          });
          setoptionsUpdate(allRole);
          getTeamInfo();
          return {
            data: resultAfterSplit,
            total: resultAfterSplit.length,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1000, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        open={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="角色类别"
            name="category"
            rules={[{ required: true, message: '请输入用户类别！' }]}
          >
            <Select
              placeholder="请选择角色类别"
              //disabled={createOrUpdate}
              options={optionsUpdate}
              onChange={(value, label) => getMenberByType(value)}
            />
          </Form.Item>
          <Form.Item
            label="用户名称"
            name="userName"
            rules={[{ required: true, message: '请输入用户名称!' }]}
          >
            <Select
              mode="multiple"
              allowClear
              placeholder="请选择团队成员"
              onChange={(value, label) => {}}
              options={allMenmer}
            />
          </Form.Item>
          <Form.Item
            label="用户ID"
            name="userId"
            hidden={true}
            //rules={[{ required: true, message: 'Please input your userId!' }]}
          >
            <Input disabled />
          </Form.Item>
          {/* <Form.Item
            label="备注"
            name="memo"
            //rules={[{ required: true, message: 'Please input your memo!' }]}
          >
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default TeamInfo;
